package com.blacktea.structuralpatterns.proxypattern.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 日志代理切面类
 * @author: black tea
 * @date: 2023/3/23 14:56
 */
@Aspect
@Component
@Slf4j
public class LogProxyAspect {

    @Pointcut("execution(* com.blacktea.structuralpatterns.proxypattern.controller.*.*(..))")
    public void pointcut() {}

    @Before("pointcut()")
    public void beforePointcut(JoinPoint joinPoint) {
        Map<String, Object> map = new HashMap<>();
        Object[] args = joinPoint.getArgs();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String[] parameterNames = signature.getParameterNames();
        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            String parameterName = parameterNames[i];
            map.put(parameterName, arg);
        }
        log.info("入参进行解析后：{}", map);
        log.info("接口调用开始，请求参数为：{}", Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(pointcut="pointcut()", returning = "result")
    public void afterReturningPointcut(JoinPoint joinPoint, Object result) {
        log.info("接口调用结束，返回结果为：{}", result);
    }

}
